import axios, {AxiosInstance, AxiosRequestConfig} from 'axios'
import {getToken, setToken} from "../plugins/cookie";
import {ElMessage} from "element-plus";
import {refreshToken} from "./common";

class HttpRequest {
    private readonly baseUrl: string;

    constructor() {
        this.baseUrl = `${import.meta.env.VITE_LOCATION_ORIGIN}/api`
    }

    getInsideConfig() {
        let config = {}
        if (getToken()) {
            config = {
                baseURL: this.baseUrl,
                headers: {
                    'Authorization': `Bearer ${getToken()}`
                }
            }
        } else {
            config = {
                baseURL: this.baseUrl,
            }
        }

        return config
    }

// 请求拦截
    interceptors(instance: AxiosInstance, url: string | number | undefined) {
        instance.interceptors.request.use(config => {
            // 添加全局的loading..
            // 请求头携带token
            return config
        }, (error: any) => {
            return Promise.reject(error)
        })
        //响应拦截
        instance.interceptors.response.use(res => {
            //返回数据
            const {data} = res
            console.log('返回数据处理', data, data.code)

            if (data.code != 0) {

                if (data.code == 31) {
                    return refreshToken().then(response => {
                        // 刷新token成功，将最新的token更新到header中，同时保存在localStorage中
                        const {token} = response.data
                        setToken(token.access_token);

                        // 获取当前失败的请求
                        const config = res.config
                        config.headers['Authorization'] = `Bearer ${token.access_token}`
                        //重试当前请求并返回promise
                        return instance(config)
                    })
                } else if (data.code == 33 || data.code == 32) {
                    ElMessage.error('登录已过期,请重新登录')
                    window.location.href = '/login'
                    return;
                } else {
                    ElMessage.error(data.message)
                    return Promise.reject(new Error(data.message || 'Error'))
                }

            } else {
                return data
            }

        }, (error: any) => {
            console.log('error==>', error)
            return Promise.reject(error)
        })
    }

    request(options: AxiosRequestConfig) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

const http = new HttpRequest()
export default http
